package com.zj.z11select.secruity.service;


import com.google.common.collect.Maps;
import com.zj.z11select.secruity.domian.LoginUser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Description token令牌
 * @Author ZHOUJIEStart
 * @Date 2021-08-03 21:57
 * @Email z-houjie@qq.com / zkanan21@gmail.com
 */
@Component
public class TokenService {

    /**
     * 令牌自定义标识
     */
    @Value("${token.header}")
    private String header;

    /**
     * 令牌秘钥
     */
    @Value("${token.secret}")
    private String secret;

    /**
     *
     令牌有效期（默认30分钟）
     */
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;


    /**
     * 创建令牌
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        Map<String, Object> claims = Maps.newHashMap();
        claims.put("user",loginUser);
        String token = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date(expireTime * MILLIS_MINUTE))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        loginUser.setToken(token);
        createLoginInfo(loginUser);
        return token;
    }

    /**
     * 验证令牌是否有效
     * 校验机制：如果token超时或不合法则抛出异常
     * @param token 令牌
     * @return 令牌
     */
    public boolean verifyToken(String token){
        Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
        return true;
    }

    /**
     * 渲染填充LoginUser
     * @param loginUser
     */
    private void createLoginInfo(LoginUser loginUser){

    }
}
